<template>
  <div>
    <t-dialog
      header="标注"
      :visible="props.visible"
      :confirm-on-enter="true"
      :on-cancel="closetable"
      :on-close="closetable"
      :cancelBtn="null"
      :closeOnEscKeydown="true"
      :confirmBtn="null"
      :loading="loading"
    >
      <template #body>
        <div class="dialog-box">
          <div class="dialog-box-left">
            <span class="dialog-box-left-title"> {{ detail.name }} </span>
            <div class="dialog-box-left-content">
              <div class="look" @click="IMGvisible = true">
                <i class="doorIcon">&#xe630;</i>
              </div>
              <img
                v-if="detail.images.length > 0"
                :src="$filters.getLinkUrl(detail.images[current].data, '?imageView2/2/w/358/h/444/format/webp')"
                alt=""
                fit="cover"
                position="center"
              />
            </div>
            <div class="dialog-box-left-dot">
              <div
                class="dot-item"
                :class="{ 'dot-item-active': index === current }"
                v-for="(item, index) in detail.images"
                :key="index"
                @click="current = index"
                :style="{ marginLeft: index === 0 ? '0px' : '8px' }"
              ></div>
            </div>
          </div>
          <div class="dialog-box-right">
            <div class="right-title">
              <span>展品标签</span>
              <i class="doorIcon">&#xe635;</i>
            </div>
            <div class="right-select">
              <t-tree-select
                :popupVisible="false"
                :defaultPopupVisible="false"
                v-model="selectList"
                :data="threeList"
                multiple
                clearable
                placeholder=""
                :tree-props="{
                  keys: {
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  },
                }"
              >
                <!-- <template #valueDisplay="{ value: valueDisplay }">
                  <t-tag v-for="(item, index) in valueDisplay" :key="index" closable @close="romoveId(index)">
                    {{ item.label }}
                  </t-tag>
                  
                </template> -->
              </t-tree-select>
            </div>
            <div class="right-tip">
              <i class="doorIcon">&#xe640;</i>
              <span>您可以基于自己的展览创建一套标签体系，最多支持三级，请在下方完成标签操作。</span>
            </div>
            <t-checkbox-group v-model="selectList">
              <div class="tree-content">
                <div class="tree-content-level1 tree-content-level">
                  <div v-for="item in threeList" :key="item.id" class="level-items" @click="setLevelId(item, 1)">
                    <div
                      class="level-items-child"
                      :class="{
                        'level-items-actives': level1Id == item.id,
                        'level-items-active': getIndexType(item.id, selectList),
                      }"
                    >
                      <t-checkbox :value="item.id" @change="addLevel1Item(item)" />

                      <span>{{ item.name }}</span>
                    </div>
                  </div>
                  <t-popconfirm @cancel="cancel" @confirm="confirm">
                    <template #content>
                      <div class="input-box">
                        <t-input v-model="parmas.name" :maxlength="20"></t-input>
                      </div>
                    </template>

                    <div class="addLevelInfo">
                      <i class="doorIcon">&#xe662;</i>
                      <span>添加一级单元</span>
                    </div>
                  </t-popconfirm>
                </div>
                <div class="tree-content-level2 tree-content-level" v-if="level2List !== null">
                  <div v-for="item in level2List" :key="item.id" class="level-items" @click="setLevelId(item, 2)">
                    <div
                      class="level-items-child"
                      :class="{
                        'level-items-actives': level2Id == item.id,
                        'level-items-active': getIndexType(item.id, selectList),
                      }"
                    >
                      <t-checkbox :value="item.id" @change="addLevel2(item.id, item)" />
                      <span>{{ item.name }}</span>
                    </div>
                  </div>
                  <t-popconfirm @cancel="cancel" @confirm="confirm2">
                    <template #content>
                      <div class="input-box">
                        <t-input v-model="parmas.name" :maxlength="20"></t-input>
                      </div>
                    </template>

                    <div class="addLevelInfo">
                      <i class="doorIcon">&#xe662;</i>
                      <span>添加二级单元</span>
                    </div>
                  </t-popconfirm>
                </div>
                <div class="tree-content-level3 tree-content-level" v-if="level3List !== null">
                  <div v-for="item in level3List" :key="item.id" class="level-items" @click="setLevelId(item, 3)">
                    <div
                      class="level-items-child"
                      :class="{
                        'level-items-actives': level3Id == item.id,
                        'level-items-active': getIndexType(item.id, selectList),
                      }"
                    >
                      <t-checkbox :value="item.id" @change="addLevel3(item.id, item)" />
                      <span>{{ item.name }}</span>
                    </div>
                  </div>
                  <t-popconfirm @cancel="cancel" @confirm="confirm3">
                    <template #content>
                      <div class="input-box">
                        <t-input v-model="parmas.name" :maxlength="20"></t-input>
                      </div>
                    </template>

                    <div class="addLevelInfo">
                      <i class="doorIcon">&#xe662;</i>
                      <span>添加三级单元</span>
                    </div>
                  </t-popconfirm>
                </div>
              </div>
            </t-checkbox-group>
            <!-- <div class="btm-tip">
              <i class="doorIcon">&#xe640;</i>
              <span class="btm-tip-title1">更多功能请前往</span>
              <span class="btm-tip-title2">展品标签管理</span>
            </div> -->
          </div>
        </div>
      </template>
      <template #footer>
        <t-button @click="closetable" theme="default" variant="outline">取消</t-button>
        <t-button @click="onSubmit" type="submit">确定</t-button>
      </template>
    </t-dialog>
    <t-image-viewer
      v-if="detail.images.length > 0"
      v-model:visible="IMGvisible"
      :images="[$filters.getLinkUrl(detail.images[current].data)]"
    >
    </t-image-viewer>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck

import { upLoadFn } from '@/utils/request/upload';
import { url, heards, urls } from '@/utils/request/upload';
import { ref, reactive, defineExpose, nextTick, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { delExbitionTag, bindTag, tagList, tagSave, tagDetail } from '@/api/tag/tag';
import { useRouter, useRoute } from 'vue-router';
import { useProjectStore, useUserStore } from '@/store';

const emit = defineEmits(['close', 'submit']);
const store = useProjectStore();
const route = useRoute();
const threeList = ref([]); //树状总列表
const selectList = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
  },
  id: {
    type: Number || String,
  },
});
const loading = ref(false);
const IMGvisible = ref(false); //图片预览
const current = ref(0); //当前激活图片
const level2List = ref(null); //二级列表
const level3List = ref(null); //三级列表
const level1Id = ref(0); //一级选中id
const level2Id = ref(0); //二级选中id
const level3Id = ref(0); //三级选中id
const detail = ref({
  id: 0,
  images: [],
  name: '',
  tagIds: [],
});
const parmas = reactive({
  id: 0,
  name: '',
  projectId: localStorage.getItem('projectId'),
  parentId: 0,
  sort: 0,
  showpieceId: 0,
});
const initInfo = async () => {
  let { data } = await tagDetail(localStorage.getItem('projectId'), props.id);
  detail.value = data;
  selectList.value = data.tagIds;
  console.log(data);
};

const init = async (type?: number) => {
  let { data } = await tagList(localStorage.getItem('projectId'));
  threeList.value = data;
  if (type) {
    let index = threeList.value.findIndex((el) => {
      return el.id === level1Id.value;
    });
    if (type === 2) {
      level2List.value = threeList.value[index].children;
    } else if (type === 3) {
      let items = threeList.value[index].children;
      let indexs = items.findIndex((el) => {
        return el.id === level2Id.value;
      });
      level3List.value = items[indexs].children;
    }
  }

  // items.value[0].children = data;
  // console.log(items.value[0].children);
};

const uploadAllFilesInOneRequest = ref(false);

const closetable = () => {
  //   visible1.value = false;

  emit('close');
};
const onSubmit = ({ validateResult, firstError }) => {
  console.log(selectList.value);
  if (loading.value) {
    return;
  }
  loading.value = true;
  bindTag(localStorage.getItem('projectId'), props.id, selectList.value).then((res) => {
    if (res.succeeded && res.statusCode) {
      MessagePlugin.success('标注修改成功');
      emit('submit');
    }
    loading.value = false;
  });
};
const setLevelId = (item: any, type: number) => {
  if (type === 1) {
    level1Id.value = item.id;
    level2List.value = item.children.length > 0 ? item.children : [];
    level3List.value = null;
    console.log(level1Id.value);
  } else if (type === 2) {
    level2Id.value = item.id;
    level3List.value = item.children.length > 0 ? item.children : [];
  } else {
    level3Id.value = item.id;
  }
};
const getIndexType = (e: number, arr: any) => {
  //判断list是否在列表中
  let index = arr.findIndex((el) => {
    return e === el.id;
  });

  if (index !== -1) {
    return true;
  } else {
    return false;
  }
};
const getSlectListType = (e: number) => {
  let index = selectList.value.findIndex((el) => {
    return el == e;
  });
  return index;
};
const romoveId = (index) => {
  let list = selectList.value;
  list.splice(index, 1);
  selectList.value = list;
};
const forDelId = (item) => {
  let arr = [];
  item.forEach((element) => {
    let idType = getSlectListType(element.id);
    if (idType !== -1) {
      selectList.value.splice(idType, 1);
      // arr.push(element.id);
      // selectList.value.push(element.id);
    }
    element.children.forEach((child) => {
      let idTypes = getSlectListType(child.id);
      if (idTypes !== -1) {
        selectList.value.splice(idTypes, 1);
        // arr.push(child.id);
        // selectList.value.push(child.id);
      }
    });
  });
  // const result = arr.filter((elem) => !selectList.value.includes(elem));
  // selectList.value = result;
  // return result;
};

const forAddId = (item) => {
  //按列表添加
  let arr = [];
  item.forEach((element) => {
    let idType = getSlectListType(element.id);
    if (idType == -1) {
      arr.push(element.id);
      // selectList.value.push(element.id);
    }
    element.children.forEach((child) => {
      let idTypes = getSlectListType(child.id);
      if (idTypes == -1) {
        arr.push(child.id);
        // selectList.value.push(child.id);
      }
    });
  });
  selectList.value = selectList.value.concat(arr);

  // console.log(arr);
};
const addLevel1Item = (item: any) => {
  //按列表删除
  setTimeout(() => {
    let indexs = selectList.value.findIndex((el) => {
      return el === item.id;
    });
    if (indexs === -1) {
      forDelId(item.children);
    } else {
      forAddId(item.children);
    }
    console.log('触发');
    // if (indexs === -1) {
    //   selectList.value.push(level1Id.value);
    // }
    // console.log(indexs, '11111111');
  }, 100);
};
const addLevel2 = (id: number, item: any) => {
  setTimeout(() => {
    let indexs = selectList.value.findIndex((el) => {
      return el === item.id;
    });
    if (indexs === -1) {
      forDelId(item.children);
    } else {
      let indexs = selectList.value.findIndex((el) => {
        return el === level1Id.value;
      });
      if (indexs === -1) {
        selectList.value.push(level1Id.value);
      }
      forAddId(item.children);
    }
  }, 100);
};
const addLevel3 = (id: number, item: any) => {
  setTimeout(() => {
    let indexs = selectList.value.findIndex((el) => {
      return el === item.id;
    });
    if (indexs === -1) {
    } else {
      let indexs = selectList.value.findIndex((el) => {
        return el === level1Id.value;
      });
      if (indexs === -1) {
        selectList.value.push(level1Id.value);
      }
      let indexs2 = selectList.value.findIndex((el) => {
        return el === level2Id.value;
      });
      if (indexs2 === -1) {
        selectList.value.push(level2Id.value);
      }
    }
  }, 100);
};
const addTag = (type: number) => {
  tagSave(parmas).then((res) => {
    if (res.data && res.statusCode === 200) {
      MessagePlugin.success('添加成功');

      parmas.name = '';
      parmas.parentId = 0;
      init(type);
    }
  });
};
const cancel = () => {};
const confirm = () => {
  parmas.parentId = 0;
  addTag();
};
const confirm2 = () => {
  parmas.parentId = level1Id.value;
  addTag(2);
};
const confirm3 = () => {
  parmas.parentId = level2Id.value;
  addTag(3);
};
watch(
  () => props.visible,
  () => {
    if (props.visible) {
      initInfo();
      init();
    }
  },
  { deep: true },
);
</script>

<style lang="less" scoped>
.dialog-box {
  display: flex;
  width: 100%;
}
.dialog-box-left {
  display: flex;
  flex-direction: column;
  width: 358px;
  margin-right: 24px;
}
.dialog-box-left-title {
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.8);
  line-height: 24px;
  margin-bottom: 8px;
}
.dialog-box-left-content {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  width: 358px;
  height: 444px;
  border-radius: 4px;
  background: #f5f5f5;
  .look {
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 60;
    width: 24px;
    height: 24px;
    background: #ffffff;
    box-shadow: 0px 1px 10px 0px rgba(0, 0, 0, 0.05), 0px 4px 5px 0px rgba(0, 0, 0, 0.08),
      0px 2px 4px -1px rgba(0, 0, 0, 0.12);
    border-radius: 12px;
    border: 1px solid #f0f0f0;
    border-radius: 50%;
    .doorIcon {
      font-size: 16px;
      color: RGBA(167, 167, 167, 1);
    }
  }
  img {
    max-width: 358px;
    max-height: 444px;
  }
}

.dialog-box-left-dot {
  display: flex;
  align-items: center;
  justify-content: center;
}
.dot-item {
  cursor: pointer;
  transition: all 0.3s;
  width: 6px;
  height: 6px;
  background: RGBA(250, 213, 209, 1);
  border-radius: 50%;
  margin-top: 12px;
}
.dot-item-active {
  width: 24px;
  height: 6px;
  background: #e62b17;
  border-radius: 3px;
}
.dialog-box-right {
  display: flex;
  flex-direction: column;
  flex: 1;
  .right-title {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    span {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.8);
      line-height: 24px;
      margin-right: 4px;
    }
    .doorIcon {
      font-size: 16px;
      color: RGBA(162, 162, 162, 1);
    }
  }
}
:deep(.t-tag-input--break-line:not(.t-is-empty) .t-input .t-input__suffix-icon) {
  display: none;
}
.right-select {
  width: 100%;
  min-height: 80px;
  margin-bottom: 12px;
}
.right-tip {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 12px 24px;
  background: #f5f5f5;
  border-radius: 6px;
  margin-bottom: 12px;
  .doorIcon {
    font-size: 24px;
    color: #e62b17;
    margin-right: 8px;
  }
  span {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.8);
    line-height: 24px;
  }
}
:deep(.t-dialog) {
  width: 1138px;
}
:deep(.t-tag-input .t-tag) {
  background: #f5f5f5;
}
:deep(.t-checkbox-group) {
  width: 602px;
  height: 292px;
}
.tree-content {
  display: flex;
  justify-content: flex-start;
  width: 602px;
  height: 292px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;

  margin-bottom: 4px;

  .tree-content-level2,
  .tree-content-level3 {
    box-shadow: inset 1px 0px 0px 0px #f0f0f0;
  }
  .tree-content-level1,
  .tree-content-level2,
  .tree-content-level13 {
    width: 200px;
    height: 288px;
  }
  .tree-content-level {
    height: 288px;
    width: 200px;
    overflow: auto;
  }
  .level-items {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 44px;
  }
  .level-items-child {
    cursor: pointer;
    display: flex;
    align-items: center;
    width: 184px;
    height: 36px;
    padding: 0 8px;
    border-radius: 4px;
    span {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.8);
      line-height: 24px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .level-items-active {
    background: #ffece6;
    span {
      color: #e62b17;
    }
  }
  .level-items-actives {
    background: #ffece6;
    span {
      color: #e62b17;
    }
  }
  .tree-content-level::-webkit-scrollbar {
    display: none;
  }
}
.btm-tip {
  display: flex;
  align-items: center;
  .doorIcon {
    font-size: 16px;
    color: RGBA(162, 162, 162, 1);
    margin-right: 3px;
  }
}

.btm-tip-title1 {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.38);
  line-height: 22px;
}
.btm-tip-title2 {
  cursor: pointer;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #e62b17;
  line-height: 22px;
  text-decoration: underline;
}
.addLevelInfo {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 168px;
  height: 36px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px dashed #d9d9d9;
  margin: 8px auto;
  cursor: pointer;
  .doorIcon {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.59);
    margin-right: 4px;
  }
  span {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.59);
    line-height: 24px;
  }
}
:deep(.t-select-input) {
  // min-height: 80px;
}
:deep(.t-tag-input) {
  // min-height: 80px;
}
:deep(.t-tag-input .t-input) {
  min-height: 80px;
  .t-input__inner {
  }
}
:deep(.t-input__input-pre) {
  display: none;
}
:deep(.t-fake-arrow) {
  display: none;
}
:deep(input::placeholder) {
  display: none;
}
</style>
